import { Component, OnInit, ViewChild, Input } from '@angular/core';
import { NzModalRef, NzMessageService, NzNotificationService } from 'ng-zorro-antd';
import { _HttpClient } from '@delon/theme';
import { SFSchema, SFUISchema, SFComponent, SFUISchemaItem } from '@delon/form';
import { Observable, of, zip } from 'rxjs';
import { catchError } from 'rxjs/operators';

/**
 * 添加/修改 作业
 */
@Component({
  selector: 'app-quartz-job-edit',
  templateUrl: './quartz-edit.component.html',
})
export class QuartzEditComponent implements OnInit {
  // 用于关闭dropmenu
  visible = false;
  @Input()
  record: any = {};
  i: any;
  job_status = [];
  job_execute_status = [];
  job_type = [];
  misfire_policy = [];
  @ViewChild('sf', { static: false }) sf: SFComponent;
  schema: SFSchema = {
    properties: {},
  };
  ui: SFUISchema = {
    '*': {
      spanLabelFixed: 100,
      grid: { span: 12 },
    },
    $misfirePolicy: {
      grid: { span: 24 },
    },
  };

  constructor(
    private modal: NzModalRef,
    private msgSrv: NzMessageService,
    public http: _HttpClient,
    private notice: NzNotificationService,
  ) {}

  ngOnInit() {
    this.buildSf();
    if (this.record.jobId) {
      this.http.get(`/cf/job/sys-job/${this.record.jobId}`).subscribe(res => {
        this.i = res.data;
      });
    }
  }

  buildSf() {
    this.schema = {
      properties: {
        jobName: { type: 'string', title: '任务名', readOnly: this.record.jobId ? true : false },
        jobGroup: {
          type: 'string',
          title: '组名',
          readOnly: this.record.jobId ? true : false,
          ui: { optionalHelp: '相同的组名下不能有重复的任务名' },
        },
        jobType: {
          type: 'string',
          title: '类型',
          enum: this.job_type,
          ui: {
            widget: 'select',
            allowClear: true,
          },
        },
        executePath: {
          type: 'string',
          title: '执行路径',
          default: ' ',
          ui: {
            optionalHelp: '选择【http接口调用】时填写url，仅支持返回类型为R的get请求; 选择【jar程序】时填写jar程序路径',
          },
        },
        className: {
          type: 'string',
          title: '执行类名',
          default: ' ',
          ui: {
            optionalHelp: '选择【java类】时填写类完整路径;选择【spring bean】时填写spring bean名称',
          },
        },
        methodName: { type: 'string', title: '执行方法' },
        methodParamsValue: { type: 'string', title: '执行参数' },
        cronExpression: {
          type: 'string',
          title: 'cron表达式',
          ui: {
            widget: 'custom',
          },
        },
        remark: { type: 'string', title: '备注' },
        misfirePolicy: {
          type: 'string',
          title: '错失策略',
          enum: this.misfire_policy,
          description: `<small>【错失周期立即执行】: 以错过的第一个频率时间立刻开始执行.重做错过的所有频率周期后,当下一次触发频率发生时间大于当前时间后，<br>再按照正常的Cron频率依次执行 <br> 【错失周期执行一次】: 以当前时间为触发频率立刻触发一次执行,然后按照Cron频率依次执行<br>【下周期执行】: 不触发立即执行,等待下次Cron触发频率到达时刻开始按照Cron频率依次执行</small>`,
          ui: {
            widget: 'select',
            allowClear: true,
          },
        },
      },
      required: ['jobName', 'jobGroup', 'jobType', 'cronExpression', 'misfirePolicy'],
      if: {
        properties: { jobType: { enum: ['3', '4'] } },
      },
      then: {
        required: ['executePath'],
      },
      else: {
        required: ['className'],
      },
    };
  }

  save(value: any) {
    if (value.executePath) {
      value.executePath = value.executePath.trim();
    }
    if (value.className) {
      value.className = value.className.trim();
    }
    if (!this.record.jobId) {
      this.http
        .get(`/cf/job/sys-job/is-valid-task-name?jobName=${value.jobName}&jobGroup=${value.jobGroup}`)
        .subscribe(res => {
          if (res.status === 200) {
            this.http
              .post(`/cf/job/sys-job`, value)
              .pipe(catchError(err => of(err)))
              .subscribe(res2 => {
                if (res2.status === 200) {
                  this.notice.success('成功', '保存成功');
                  this.modal.close(true);
                }
              });
          } else {
            this.notice.error('错误', `【${value.jobName}】在【${value.jobGroup}】内已经存在同名任务`);
          }
        });
    } else {
      this.http
        .put(`/cf/job/sys-job`, value)
        .pipe(catchError(err => of(err)))
        .subscribe(res2 => {
          if (res2.status === 200) {
            this.notice.success('成功', '保存成功');
            this.modal.close(true);
          }
        });
    }
  }

  close() {
    this.modal.destroy();
  }
}
